package Demo;


import java.util.Random;

class MyBlockingQueue {
    private int[] arr;
    private int head = 0;
    private int tail = 0;
    private int size = 0;

    private static Object locker = new Object();
    public MyBlockingQueue(int capacity) {
        arr = new int[capacity];
    }
    public MyBlockingQueue() {
        arr = new int[1000];
    }

    public void put(int val) throws InterruptedException {
       synchronized (locker) {
           while (size >= arr.length) {
               locker.wait();
           }
           arr[tail] = val;
           tail++;
           if (tail >= arr.length) {
               tail = 0;
           }
           size++;
           locker.notifyAll();
       }
    }

    public int take() throws InterruptedException {
        synchronized (locker) {
            while (size <= 0) {
                locker.wait();
            }
            int val = arr[head];
            head++;
            if (head >= arr.length) {
                head = 0;
            }
            size--;
            locker.notifyAll();
            return val;
        }
    }



}

public class Demo03 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue q = new MyBlockingQueue();

        Thread customer = new Thread( () -> {
           while (true) {
               try {
                   int val = q.take();
                   System.out.println("消费元素: " + val);
                   Thread.sleep(1);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        Thread producer = new Thread( () -> {
           Random random = new Random();
           while (true) {
               try {
                   int num = random.nextInt(100);
                   System.out.println("生产元素: " + num);
                   q.put(num);
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });

        customer.start();
        producer.start();

        customer.join();
        producer.join();

    }
}
